######################
##### PREPARATION ####
######################
# Clear environment
rm(list=setdiff(ls(), "path_to"))

# Load data
s = readRDS(path_to("robustness_beliefs"))


###############################
#### DERIVE DATA: BELIEFS #####
###############################
# Anticipated effects
df = s %>% group_by(condition, effect) %>%
  summarise(n = n()) %>%
  mutate(
    freq = n / sum(n, na.rm=T), effect=factor(effect)
  )

# Labels
df$label = ifelse(
  df$freq >= 0.005,
  paste0(round(df$freq*100), "%"),
  paste0(round(df$freq*100, 1), "%")
)
df$ypos = sapply(1:nrow(df), function(x) {
  1 - sum(df$freq[as.numeric(df$effect) < as.numeric(df$effect[x]) & df$condition == df$condition[x]]) -
    df$freq[x]/2
})


####################################
#### DERIVE DATA: EXPLANATIONS #####
####################################
# Anticipated effects
df_explain = s %>% group_by(condition, code_effect_simple) %>%
  summarise(n = n()) %>%
  mutate(
    freq = n / sum(n, na.rm=T),
  )
df_explain$code_effect_simple = factor(df_explain$code_effect_simple, levels=c("other", "spillover", "naive", "dampening"))

# Labels
df_explain$label = ifelse(
  df_explain$freq >= 0.005,
  paste0(round(df_explain$freq*100), "%"),
  paste0(round(df_explain$freq*100, 1), "%")
)
df_explain$number = plyr::mapvalues(df_explain$code_effect_simple, from=c("other", "spillover", "naive", "dampening"), to=c(1:4)) %>%
  as.numeric
df_explain$ypos = sapply(1:nrow(df_explain), function(x) {
  1 - sum(df_explain$freq[df_explain$number < df_explain$number[x] & df_explain$condition == df_explain$condition[x]]) -
    df_explain$freq[x]/2
})

# Don't display other fraction
df_explain = df_explain %>% filter(code_effect_simple != "other")


######################
#### PLOT ############
######################
plots = subplots = list()
for (cond in c("numeric", "production", "beliefs_incentives")) {
  subplots[[paste0("beliefs_", cond)]] = ggplot(df[df$condition == cond, ], aes(x = 1, y = freq, fill = effect, label = label)) +
    geom_bar(stat = "identity") +
    geom_text(aes(y = ypos), family="rob_con", size = 4) +
    xlab("Belief") + ylab("Frequency") +
    coord_cartesian(ylim=c(0, 1)) +
    scale_y_continuous(breaks=seq(0, 1, 0.2), labels=paste0(100*seq(0, 1, 0.2), "%")) +
    scale_fill_manual(
      values=c("darkolivegreen2", "skyblue", "orange2", "red2", "red4"),
      labels=c("decreases by more", "decreases one-to-one", "decreases by less", "does not change", "actually increases"),
      name = "**Belief**: In response to decrease in own<br>consumption, aggregate consumption ..."
    ) +
    theme_minimal() +
    theme(
      text = element_text(family = "rob_con"),
      plot.title = element_blank(),#element_text(size=18, face="bold", hjust=0.5),
      legend.position = "bottom",
      legend.direction = "vertical",
      legend.title = element_markdown(size=12, hjust=0),
      #legend.spacing.y = unit(0, 'cm'),
      panel.grid.major.x = element_blank(),
      panel.grid.minor = element_blank(),
      axis.title = element_text(face="bold", size=14),
      axis.text.x = element_blank(),
      axis.text.y = element_text(size=14),
      legend.text = element_text(size=12)
    ) +
    guides(fill = guide_legend(nrow = 5))
  
  subplots[[paste0("explanation_", cond)]] = ggplot(df_explain[df_explain$condition == cond, ], aes(x = 1, y = freq, fill = code_effect_simple, label = label)) +
    geom_bar(stat = "identity") +
    geom_text(aes(y = ypos), family="rob_con", size = 4) +
    xlab("Explanation") + ylab("Frequency") +
    coord_cartesian(ylim=c(0, 1)) +
    scale_y_continuous(breaks=seq(0, 1, 0.2), labels=paste0(100*seq(0, 1, 0.2), "%")) +
    scale_fill_manual(
      values=c("darkolivegreen2", "skyblue", "red2"),
      labels=c("positive multiplier  ", "direct aggregate impact  ", "dampened aggregate impact"),
      name = "**Explanation**: Respondents explain a ..."
    ) +
    theme_minimal() +
    theme(
      text = element_text(family = "rob_con"),
      plot.title = element_text(size=18, face="bold", hjust=0.5),
      legend.position = "bottom",
      legend.direction = "vertical",
      legend.title = element_markdown(size=12, hjust=0),
      #legend.spacing.y = unit(0, 'cm'),
      panel.grid.major.x = element_blank(),
      panel.grid.minor = element_blank(),
      axis.title = element_text(face="bold", size=14),
      axis.text.x = element_blank(),
      axis.text.y = element_text(size=14),
      legend.text = element_text(size=12)
    ) +
    guides(fill = guide_legend(nrow = 3, reverse = F))
  
  plots[[paste0("fig_", cond)]] = subplots[[paste0("beliefs_", cond)]] & subplots[[paste0("explanation_", cond)]]
  
  # Save generated graph.
  pdf(path_to("figures", paste0("fig_", cond, ".pdf")), width=6, height=5.5)
  print(plots[[paste0("fig_", cond)]])
  dev.off()  
}


